package com.fh.binarysearch;

/**
 * T35.搜索插入位置
 * @author: fuhao
 * @date: 2025/10/14 21:47
 */
public class T35SearchInsert {

    class Solution {
        public int searchInsert(int[] nums, int target) {
            int left = 0;
            int right = nums.length - 1;

            while (left <= right) {
                int mid = left + (right - left) / 2; // 防止溢出
                if (nums[mid] == target) {
                    return mid; // 找到目标，直接返回索引
                } else if (nums[mid] < target) {
                    left = mid + 1; // 目标在右侧，缩小左边界
                } else {
                    right = mid - 1; // 目标在左侧，缩小右边界
                }
            }
            // 未找到目标，left即为应插入的位置
            return left;
        }
    }
}
